package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.module.admin.entity.SysInfoConversion;
import com.mars.module.admin.mapper.SysInfoConversionMapper;
import com.mars.module.admin.request.SysInfoConversionRequest;
import com.mars.module.admin.service.ISysInfoConversionService;
import com.mars.module.utils.GetFontUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 资料转换记录业务层处理
 *
 * @author mars
 * @date 2024-04-08
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysInfoConversionServiceImpl implements ISysInfoConversionService {

    private final SysInfoConversionMapper baseMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysInfoConversion add(SysInfoConversionRequest request) {
        SysInfoConversion entity = SysInfoConversion.builder().build();
        BeanUtils.copyProperties(request, entity);
        Long userId = ContextUserInfoThreadHolder.get().getId();
        entity.setCreateById(userId);
        //解析图片
        GetFontUtil util = new GetFontUtil();
        String picture = request.getPicture();
        //String newUrl = "/Users/caijin/Downloads/" + picture.substring(picture.lastIndexOf("/") + 1, picture.length());
        // 指定文件夹路径
        String folderPath = "D://picture//";
        // 创建File对象
        File folder = new File(folderPath);
        // 判断文件夹是否存在
        if (!folder.exists()) {
            // 文件夹不存在，创建文件夹
            folder.mkdirs();
        }
        String newUrl = folderPath + picture.substring(picture.lastIndexOf("/") + 1, picture.length());
        util.downloadFile(request.getPicture(), newUrl);
        String content = GetFontUtil.getImgString(newUrl, "1");
        entity.setContent(content);
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysInfoConversionRequest request) {
        SysInfoConversion entity = SysInfoConversion.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysInfoConversion getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysInfoConversion> pageList(SysInfoConversionRequest request) {
        Page<SysInfoConversion> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysInfoConversion> query = this.buildWrapper(request);
        IPage<SysInfoConversion> pageRecord = baseMapper.selectPage(page, query);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysInfoConversion> list(SysInfoConversionRequest request) {
        LambdaQueryWrapper<SysInfoConversion> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    @Override
    public void exportWord(HttpServletResponse response, List<Long> id) throws IOException {
        // 创建一个空的Word文档
        XWPFDocument document = new XWPFDocument();
        List<SysInfoConversion> sysTextCorrects = baseMapper.selectList(new QueryWrapper<SysInfoConversion>().lambda().in(SysInfoConversion::getId, id));
        for (SysInfoConversion correct : sysTextCorrects) {
            // 创建一个段落
            XWPFParagraph paragraph = document.createParagraph();
            paragraph.createRun().setText(correct.getContent());
        }
        // 将文档写入到输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        document.write(out);
        byte[] bytes = out.toByteArray();
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "infoConversion.docx");
        // 将文档作为响应返回
        response.setHeader("Content-Disposition", "attachment; filename=infoConversion.docx");
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        // 写入字节并清空缓冲区
        response.getOutputStream().write(bytes);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    private LambdaQueryWrapper<SysInfoConversion> buildWrapper(SysInfoConversionRequest param) {
        LambdaQueryWrapper<SysInfoConversion> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getPicture())) {
            query.like(SysInfoConversion::getPicture, param.getPicture());
        }
        if (StringUtils.isNotBlank(param.getContent())) {
            query.like(SysInfoConversion::getContent, param.getContent());
        }
        return query;
    }

}
